package com.hyc.serviceRegister;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.hyc.constant.NacosConstant;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.Properties;

/**
 * @author 冷环渊
 * @date 2025/6/9 14:54
 * @description NacosServiceRegister
 */
public class NacosServiceRegister {
    private NamingService namingService;
    //命名空间
    private String nameScope;

    public NacosServiceRegister(String nameScope) {
        this.nameScope = nameScope;
        init();
    }

    public void init() {
        try {
            Properties properties = new Properties();
            properties.setProperty("username", NacosConstant.NACOS_USERNAME);
            properties.setProperty("password", NacosConstant.NACOS_PASSWORD);
            properties.setProperty("serverAddr", NacosConstant.SERVER_ADDR);
            if (nameScope != null) {
                properties.setProperty("namespace", nameScope);
            }
            namingService = NamingFactory.createNamingService(properties);
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
    }

    public void register(String serviceName, InetSocketAddress serviceAddress, String clusterName, Map<String, String> metadata) {
        //创建实例
        Instance instance = new Instance();
        instance.setIp(serviceAddress.getHostName());
        instance.setPort(serviceAddress.getPort());
        instance.setServiceName(serviceName);
        if (clusterName != null && !clusterName.isEmpty()) {
            instance.setClusterName(clusterName);
        }
        if (metadata != null && !metadata.keySet().isEmpty()) {
            instance.setMetadata(metadata);
        }
        try {
            namingService.registerInstance(serviceName, NacosConstant.RPC_GROUP_NAME, instance);
            System.out.println("服务注册成功：" + serviceName + " " + serviceAddress);
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
    }
}
